package com.own.component.common.model;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * UpdateModel
 *
 * @author chenxueli
 * @date 2024-01-18 15:28:31
 */
@Schema(title = "修改添加结果类")
@Getter
@Setter
@ToString
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class UpdateModel<T> implements Serializable {

    @Schema(title = "更新标志")
    private Boolean flag;

    @Schema(title = "更新后的内容")
    private T data;

    @Schema(title = "更新错误的提示语")
    private String message;

    public UpdateModel(boolean flag) {
        this.flag = flag;
    }

    public UpdateModel(boolean flag, T data, String message) {
        this.flag = flag;
        this.data = data;
        this.message = message;
    }

    public UpdateModel(boolean flag, T data) {
        this.flag = flag;
        this.data = data;
    }

    public UpdateModel(T data) {
        this.flag = true;
        this.data = data;
    }

    public boolean isSuccess() {
        return flag != null && flag;
    }

    public boolean isError() {
        return !isSuccess();
    }

    public UpdateModel<Boolean> check(boolean... flagArray) {
        for (var flag : flagArray) {
            if (!flag) {
                return new UpdateModel<>(false);
            }
        }
        return new UpdateModel<>(true);
    }

    @SafeVarargs
    public final UpdateModel<Boolean> check(UpdateModel<Boolean>... flagArray) {
        for (var model : flagArray) {
            if (!model.getFlag()) {
                return new UpdateModel<>(false);
            }
        }
        return new UpdateModel<>(true);
    }

    public UpdateModel<List<T>> convertList() {
        UpdateModel<List<T>> updateModel = new UpdateModel<>();
        updateModel.setFlag(flag);
        updateModel.setMessage(message);
        var list = new ArrayList<T>();
        list.add(data);
        updateModel.setData(list);
        return updateModel;
    }

    public UpdateModel<Boolean> toFlag() {
        return new UpdateModel<>(flag);
    }

}
